﻿
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.Diagnostics;
using Emgu.CV;
using Emgu.CV.CvEnum;
using PipeDetection.Model;
using System.IO;
using Emgu.CV.Structure;
using PipeDetection.UI.接口;

namespace PipeDetection.UI
{
    public partial class FrmVideoPlay : UIPage,Ipage
    {
 
        Capture cap;
        int fps;                    //影片帧率
        int numFrames;              //影片总帧数
        int videoWidth;             //影片宽度
        int videoHeight;            //影片高度
        int currentFrame = 0;       //当前帧
        bool isStart = false;       //是否播放
        float bs = 1;
        Stopwatch sw = new Stopwatch();
        private bool isCodeChangingValue = false;
        public FrmVideoPlay()
        {
            InitializeComponent();
            Application.Idle += Application_Idle;
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            if (uiButton1.Text == "播放")
            {
                Play(1);
            }
            else
            {
                Pause();
             
            }  
        }
        private void Application_Idle(object sender, EventArgs e)
        {
            if (!isStart) return;
            Mat a = cap.QueryFrame();
            if (a != null)
            {
                imageBox1.Image = a;
                currentFrame=(int)cap.GetCaptureProperty(CapProp.PosFrames);
                sw.Stop();
                var slp = (int)(1000.0 / fps / bs - sw.ElapsedMilliseconds);
                if(slp>0)                System.Threading.Thread.Sleep(slp);
                isCodeChangingValue = true;
                uiTrackBar1.Value = currentFrame;
                uiLabel1.Text = $"{currentFrame}/{numFrames} {fps}fps ";
                GC.Collect();
                sw.Restart();
            }

        }
        public void Open(string filename)
        {
            cap = new Capture(filename);     //读入视频
            Play(1);
            fps = (int)cap.GetCaptureProperty(CapProp.Fps);                     //获取视频帧率
            numFrames = (int)cap.GetCaptureProperty(CapProp.FrameCount);        //获取视频总帧数
            uiTrackBar1.Maximum = numFrames;
            videoWidth = (int)cap.GetCaptureProperty(CapProp.FrameWidth);       //获取视频宽度
            videoHeight = (int)cap.GetCaptureProperty(CapProp.FrameHeight);     //获取视频高度
            inspection.Fps = fps;
            inspection.Frames = numFrames;
            inspection.VideoWidth = videoWidth;
            inspection.VideoHeight = videoHeight;
            PropertyChanged?.Invoke(this, EventArgs.Empty);
        }

        private void uiButton4_Click(object sender, EventArgs e)
        {
            Play(0.5f);
        }
        private void Pause()
        {
            uiButton1.Text = "播放";
            isStart = false;
            btnnext.Visible = true;
            btnpre.Visible = true;
            //显示定义的范围
            pictureBox1.Visible = true;
            var bmp = (Bitmap)imageBox1.Image.Bitmap.Clone();
            Graphics graphics = Graphics.FromImage(bmp);
            if (inspection.DefectRect != Rectangle.Empty)
            {
                graphics.DrawRectangle(Pens.Red, inspection.DefectRect);

            }
            if (inspection.StaTionRect != Rectangle.Empty)
            {
                graphics.DrawRectangle(Pens.Red, inspection.StaTionRect);

            }
            if (inspection.SectionRect != Rectangle.Empty)
            {
                graphics.DrawRectangle(Pens.Red, inspection.SectionRect);

            }
            graphics.Dispose();
            pictureBox1.Image = bmp;
        }

        private void uiTrackBar1_ValueChanged(object sender, EventArgs e)
        {
            if (!isCodeChangingValue)
            {
                // 这是由人为操作引起的值变化
                cap?.SetCaptureProperty(CapProp.PosFrames, uiTrackBar1.Value);
                Mat a = cap.QueryFrame();
                if (a != null) imageBox1.Image = a;
                Pause();
            }
            else
            {
                // 这是由代码设置值引起的
                isCodeChangingValue = false;
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            Play(fps);
        }
   
/// <summary>
/// 播放视频，指定倍速
/// </summary>
/// <param name="b"></param>
        private void Play(float b)
        {
            uiButton1.Text = "暂停";
            bs = b;
            isStart = true;
            btnnext.Visible = false;
            btnpre.Visible = false;
            sw.Restart();
            if (pictureBox1.Visible) pictureBox1.Visible = false;
        }

        private void uiTrackBar1_MouseMove(object sender, MouseEventArgs e)
        {
           
            uiToolTip1.SetToolTip(uiTrackBar1, $"{TimeSpan.FromMilliseconds(currentFrame * 1000.0 / fps)}");
        }
        private PipeSectionInspection inspection;

        public event EventHandler PropertyChanged;

        public void InitD(object obj)
        {
            if (obj != null)
            {
                inspection = (PipeSectionInspection)obj;
                if (inspection.VideoFile != "" && File.Exists(inspection.VideoFile))
                    Open(inspection.VideoFile);
                else
                {
                    if (cap != null)
                    {
                        isStart = false;
                        cap.Stop();
                        cap = null;
                        imageBox1.Image = null;
                        uiLabel1.Text = "";
                    }
                }
            }
        }
  

        private void uiButton5_Click(object sender, EventArgs e)
        {
            uiButton5.Enabled= false;
            isStart = false;
            pictureBox1.Image= imageBox1.Image.Bitmap;
          
            var q1 = DrawHelper.GetPoints(Gtype.矩形, pictureBox1);
         
            inspection.DefectRect= Common.ConvertToRect(q1);
        
            PropertyChanged?.Invoke(this, EventArgs.Empty);
            uiButton5.Enabled = true;
        }

        private void uiButton6_Click(object sender, EventArgs e)
        {
            uiButton6.Enabled = false;
            isStart = false;
   
            pictureBox1.Image = imageBox1.Image.Bitmap;
            var q1 = DrawHelper.GetPoints(Gtype.矩形, pictureBox1);
            inspection.StaTionRect = Common.ConvertToRect(q1);
             PropertyChanged?.Invoke(this, EventArgs.Empty);
            uiButton6.Enabled = true;
        }

        private void uiButton7_Click(object sender, EventArgs e)
        {
            uiButton7.Enabled = false;
            isStart = false;

            pictureBox1.Image = imageBox1.Image.Bitmap;
            var q1 = DrawHelper.GetPoints(Gtype.矩形, pictureBox1);
            inspection.SectionRect = Common.ConvertToRect(q1);
                   PropertyChanged?.Invoke(this, EventArgs.Empty);
            uiButton7.Enabled = true;
        }

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            uiLabel1.Text = $"{e.Location}";
        }

        private void uiButton9_Click(object sender, EventArgs e)
        {
            var val = 30;
            if (Globel.pipeSectionInspection.OutDir != "" && System.IO.Directory.Exists(Globel.pipeSectionInspection.OutDir))
            {
                if (UIInputDialog.ShowInputIntegerDialog(this, ref val, true, "输入提取间隔(秒/帧)：", true))
                {
                    isStart = false;
                    pictureBox1.Visible = false;
                    var cf = 1;
                    while (cf<numFrames)
                    {
                        uiLabel1.Text = $"{cf}/{numFrames}";
                        isCodeChangingValue = true;
                        uiTrackBar1.Value = currentFrame;
                        cap?.SetCaptureProperty(CapProp.PosFrames, cf);
                        var m = cap?.QueryFrame();
                        if (m != null)
                        {
                             var img=m.ToImage<Bgr, byte>();
                            imageBox1.Image = img;
                            var section=img.GetSubRect(Globel.pipeSectionInspection.SectionRect);
                            var station=img.GetSubRect(Globel.pipeSectionInspection.StaTionRect);
                            //todo:识别断面里程，保存断面图像，dxf文件
                        }
                        cf += val * fps;
                        Application.DoEvents();
                    }
                    GC.Collect();
                    UIMessageBox.ShowInfo("保存完成！", true);
                }
               
            }
          
           
        }

        private void btnpre_Click(object sender, EventArgs e)
        {
            cap?.SetCaptureProperty(CapProp.PosFrames, --currentFrame );
            Mat a = cap.QueryFrame();
            if (a != null)    imageBox1.Image = a;
            Pause();
            }

        private void btnnext_Click(object sender, EventArgs e)
        {
            cap?.SetCaptureProperty(CapProp.PosFrames, ++currentFrame );
            Mat a = cap.QueryFrame();
            if (a != null) imageBox1.Image = a;
            Pause();
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            ((UIForm)this.ParentForm).RemovePage(this.PageIndex);
        }
    }
}
